package com.simplenix.nicasio.misc;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XMLUtil {

	public static Document novoDocumento() {
		return DocumentHelper.createDocument();
	}

	public static String xmlToString(Document documento) throws IOException {
		return xmlToString(documento, "iso-8859-1");
	}

	public static String xmlToString(Document documento, String charset) throws IOException {
		OutputFormat of = OutputFormat.createCompactFormat();
		of.setEncoding(charset);
		StringWriter wr = new StringWriter();
		XMLWriter xw = new XMLWriter(wr, of);
		xw.write(documento);
		return wr.getBuffer().toString();
	}

	public static File xmlToFile(Document documento, String nome) throws IOException {
		return xmlToFile(documento, nome, "iso-8859-1");
	}

	public static File xmlToFile(Document documento, String nome, String charset) throws IOException {
		nome = nome.replace(".xml", "");
		File f = new File(nome + ".xml");
		if (f.exists()) {
			f.delete();
		}
		OutputFormat of = OutputFormat.createCompactFormat();
		of.setEncoding(charset);
		FileWriter fr = new FileWriter(f);
		documento.write(fr);
		fr.close();
		File rtn = new File(f.getAbsolutePath());
		return rtn;
	}

	public static Document fileToXml(File f) throws MalformedURLException, DocumentException {
		SAXReader reader = new SAXReader(false);
		Document doc = reader.read(f);
		return doc;
	}

	public static org.w3c.dom.Document stringToXml(String xml) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = dbf.newDocumentBuilder();
		return builder.parse(new InputSource(new StringReader(xml)));
	}

}